﻿
using System.Collections.Generic;
using UnityEngine;

namespace Assets.Scripts.App
{
    public static class Singletons
    {
        private static readonly Dictionary<string, MonoBehaviour> SingletonsDic = new Dictionary<string, MonoBehaviour>();
        public static T Get<T>(string name) where T : MonoBehaviour
        {

            MonoBehaviour singleton;
            SingletonsDic.TryGetValue(name, out singleton);
            if (singleton == null)
            {
                GameObject newGo = new GameObject(name);
                singleton = newGo.AddComponent<T>();
                SingletonsDic.Add(name, singleton);
            }
            return singleton as T;
        }
        public static void Destroy(string name)
        {
            MonoBehaviour singleton;
            SingletonsDic.TryGetValue(name, out singleton);
            if (singleton != null)
            {
                SingletonsDic.Remove(name);
                Object.DestroyImmediate(singleton.gameObject);
            }
        }
        public static void Clear()
        {
            List<string> keys = new List<string>();
            foreach (var key in SingletonsDic.Keys)
            {
                keys.Add(key);
            }
            foreach (var key in keys)
            {
                Destroy(key);
            }
        }

    }
}
